package me.shurufa.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import me.shurufa.R;
import me.shurufa.model.AddDigestBean;
import me.shurufa.utils.Constants;
import me.shurufa.utils.LogUtils;
import me.shurufa.widget.MaskSurfaceView;
import me.shurufa.widget.colordialog.PromptDialog;

/**
 * 作者 : andy
 * 日期 : 16/3/14 14:19
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 新版相机界面 横屏
 */
public class NewCameraActivity extends BaseLandscapeActivity implements View.OnClickListener, SurfaceHolder.Callback, Camera.PictureCallback, Camera.ShutterCallback {

    @Bind(R.id.sfc_preview)
    SurfaceView sfcPreview;

    @Bind(R.id.btn_write)
    TextView btnWrite;

    @Bind(R.id.btn_shutter)
    TextView btnShutter;

    @Bind(R.id.btn_choose_pic)
    TextView btnChoosePic;

    @Bind(R.id.camera_back)
    ImageView cameraBack;

    MaskSurfaceView maskSurfaceView;

    /** 睡眠时间 */
    protected static final long SLEEP_TIME = 50;
    /** 初始化相机 */
    protected static final int MSG_ID_CAMERA_START = 0x01;
    /** 释放相机资源 */
    protected static final int MSG_ID_CAMERA_STOP = 0x2;

    boolean mIsActivityTeady = false;
    boolean mIsSurfaceTeady = false;
    SurfaceHolder mHolder;

    Camera.Parameters mParameters;
    Camera mCamera;
    /** 支持的闪光灯模式 */
    List<String> mSupportFlash;
    int mIndexFlash;
    WindowManager wm;
    int width,height;
    private long bookId;
    private boolean isKnowBookId;

    private AddDigestBean mAddDigestBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_new_camera;
        super.onCreate(savedInstanceState);
        parseArguments();
        wm = this.getWindowManager();
        height = wm.getDefaultDisplay().getWidth();   // 横屏  宽高相反
        width = wm.getDefaultDisplay().getHeight();
        bookId = getIntent().getLongExtra(Constants.ARG_BOOK_ID, 0);
        if (bookId!=0)
            isKnowBookId = true;
        uiInit();
    }

    /**
     * 传参
     * @param in
     * @param addDigestBean
     */
    public static void initArguments(Intent in, AddDigestBean addDigestBean) {
        in.putExtra(Constants.ARG_ADD_DIGEST, addDigestBean);
    }

    /**
     * 解析参数
     */
    private void parseArguments() {
        this.mAddDigestBean = (AddDigestBean) getIntent().getSerializableExtra(Constants.ARG_ADD_DIGEST);
    }


    private void uiInit() {
        cameraBack.setOnClickListener(this);
        btnWrite.setOnClickListener(this);
        btnShutter.setOnClickListener(this);
        // btnFlash.setOnClickListener(this);
        btnChoosePic.setOnClickListener(this);
        sfcPreview.getHolder().addCallback(this);
        sfcPreview.setOnClickListener(this);
        mHolder = sfcPreview.getHolder();
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        maskSurfaceView = (MaskSurfaceView)findViewById(R.id.mask_view);
        maskSurfaceView.setMaskSize(width*5/6,height/3);
    }

    /**
     * 相机为SurfaceView 要跟随生命周期
     */
    @Override
    protected void onStart() {
        super.onStart();
        mIsActivityTeady = true;
        mHandler.sendEmptyMessage(MSG_ID_CAMERA_START);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // RefWatcher refWatcher = MainApplication.getRefWatcher(this);
        // refWatcher.watch(this);
    }


    /* public void setDeniFlashMode(){
        int index = (mIndexFlash + 1) % mSupportFlash.size();

        String mode = mSupportFlash.get(index);
        if ("off".equals(mode)) {
            btnFlash.setText("off");
            mParameters.setFlashMode(mode);
            mCamera.setParameters(mParameters);
            mIndexFlash = mSupportFlash.indexOf(mode);
        } else if ("on".equals(mode)) {
            btnFlash.setText("on");
            mParameters.setFlashMode(mode);
            mCamera.setParameters(mParameters);
            mIndexFlash = mSupportFlash.indexOf(mode);
        } else if ("auto".equals(mode)) {
            btnFlash.setText("auto");
            mParameters.setFlashMode(mode);
            mCamera.setParameters(mParameters);
            mIndexFlash = mSupportFlash.indexOf(mode);
        } else {
            mIndexFlash = mSupportFlash.indexOf(mode);
            setDeniFlashMode();
        }
    }*/

    private static final int PICK_PHOTO = 0x12;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //相册选择完成后，返回图片路径 打开剪裁页面
        if (requestCode == PICK_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                if (result != null && result.size() > 0) {
                    FileOutputStream fos = null;
                    Intent intent = new Intent(this, CropImageActivity.class);
                    String path = result.get(0);
                    if (mAddDigestBean == null) {
                        mAddDigestBean = new AddDigestBean();
                        mAddDigestBean.bookId = bookId;
                    }
                    CropImageActivity.initArguments(intent, path, mAddDigestBean);
                    intent.putExtra(Constants.EXTRA_CAMERA_PHOTO, path);
                    if (bookId != 0L) {
                        intent.putExtra(Constants.ARG_BOOK_ID, bookId);
                    }
                    startActivity(intent);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            /*case R.id.btn_flash:
                setDeniFlashMode();
                break;*/
            case R.id.btn_choose_pic:
                // TODO: 16/3/27 从相册选图
                intent = new Intent(this, PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, false);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_SINGLE);
                intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
                startActivityForResult(intent, PICK_PHOTO);
                break;
            case R.id.btn_shutter:
                /*
				 * shutter:快门回调，在按下快门的瞬间会调用此接口中的方法， 常用于播放自定义的快门
				 * raw：照片回调，将未经处理的最原始的照片数据信息传递给此接口
				 * postview：照片回调，将经过一定处理的照片数据信息传递给此接口 此处理一般是经过硬件处理，所以部分手机可能不支持。
				 * jpeq 照片回调 ：将经过较大压缩的照片数据传递给此接口。最常用的接口
				 */
                if (!singleClick) {
                    singleClick=true;
                    if (mCamera == null) {
                        return;
                    }
                    mCamera.takePicture(this, null, null, this);
                }
                break;
            case R.id.btn_write:
                mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
                /*intent = new Intent(NewCameraActivity.this,BitmapNoTransformActivity.class);
                if (bookId!=0L) {
                    intent.putExtra(Constants.ARG_BOOK_ID, bookId);
                }
                startActivity(intent);
                finish();*/
                if (mAddDigestBean == null) {
                    mAddDigestBean = new AddDigestBean();
                }
                if (0 != bookId) {
                    mAddDigestBean.bookId = bookId;
                }
                mAddDigestBean.type = Constants.DIGEST_TYPE_TEXT; // 文本模式
                intent = new Intent(this, BookDigiestAddNoteActivity.class);
                BookDigiestAddNoteActivity.initArguments(intent, "", mAddDigestBean);
                // if (bookId != 0L) {
                //     intent.putExtra(Constants.ARG_BOOK_ID, bookId);
                // }
                startActivity(intent);
                finish();

                break;
            case R.id.sfc_preview:
                //调用autoFocus方法可以进行自动对焦
                //参数是个回调，用于确认对焦是否成功，如果无需知道对焦是否成功，设置为null
                // mCamera.autoFocus(null);
                break;
            case R.id.camera_back:
                mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
                finish();
                break;
            default:
                break;
        }

    }
    //  SurfaceView callback method start---->
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Canvas canvas = mHolder.lockCanvas();
        canvas.drawColor(Color.BLACK);
        mHolder.unlockCanvasAndPost(canvas);
        mIsSurfaceTeady = true;
        mHandler.sendEmptyMessage(MSG_ID_CAMERA_START);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera=null;
        mIsSurfaceTeady = false;
        mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
    }
//    SurfaceView callback method end --->
//    Camera implements method callback  start----->

    /**
     * @param data
     *            字节数组，包含照片的数据
     * @param camera
     *            刚进行拍照的相机
     * */
    boolean singleClick;
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        FileOutputStream fos = null;
        // 用于创建临时文件
        try {
            mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);

//
            Bitmap bitmap = noCutImage(data);
//                        cutImage(data);
//
            File file = File.createTempFile("DCIM", ".tmp");
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            //Intent intent = new Intent(this, BitmapTransformActivity.class);
            Intent intent = new Intent(this, CropImageActivity.class);

            if (mAddDigestBean == null) {
                mAddDigestBean = new AddDigestBean();
                mAddDigestBean.bookId = bookId;
            }

            CropImageActivity.initArguments(intent, file.getAbsolutePath(), mAddDigestBean);
            intent.putExtra(Constants.EXTRA_CAMERA_PHOTO, file.getAbsolutePath());
            if (bookId != 0L) {
                intent.putExtra(Constants.ARG_BOOK_ID, bookId);
            }
            startActivity(intent);
            finish();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得Bitmap
     * @param data
     * @return
     */
    private Bitmap getBitmap(byte[] data) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        return bitmap;
    }

    private Bitmap noCutImage(byte[] data){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);
        System.gc();
        return bitmap;
    }

    private Bitmap cutImage(byte[] data){
        //Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        BitmapFactory.Options options =new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);
        Matrix matrix = new Matrix();
        matrix.reset();
        // matrix.setRotate(90);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        System.gc();
        bitmap = Bitmap.createScaledBitmap(bitmap,sfcPreview.getWidth(),sfcPreview.getHeight(),true);
        System.gc();
        if(maskSurfaceView == null){
            return bitmap;
        }else{
            int[] sizes = maskSurfaceView.getMaskSize();
            if(sizes[0]==0 || sizes[1]==0){
                return bitmap;
            }
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            LogUtils.kLog().e("maskWidth:"+sizes[0]+",maskHeight:"+sizes[1]);
            LogUtils.kLog().e("bitmapWidth:"+w+",bitmapHeight:"+h);
            int screenWitdh = sfcPreview.getWidth();
            int screenHeight = sfcPreview.getHeight();
            LogUtils.kLog().e("screenWidth:"+screenWitdh+",screenHeight:"+screenHeight);
//            int x = (w-sizes[0])/2;
//            int y = (h-sizes[1])/2;
//            return Bitmap.createBitmap(bitmap, x, y,sizes[0], sizes[1]);
            int sizeWidth = w/screenWitdh * sizes[0];
            int sizeHeight = h/screenHeight * sizes[1];
            LogUtils.kLog().e("sizeWidth:"+sizeWidth+",sizeHeight:"+sizeHeight);
            int x = (w-sizeWidth)/2;
            int y = (h-sizeHeight)/2;
            return  Bitmap.createBitmap(bitmap,x,y,sizeWidth,sizeHeight);
            //return  Bitmap.createBitmap(bitmap,x,y,w,h);
        }
    }

    /**
     * 快门按下回调
     */
    @Override
    public void onShutter() {

    }
//    Camera implements method callback end------>

    int showDialogTimes;
    private void startCamera() {
        // 如果相机在短时间内重复打开，先关闭一下就不会出错了；
        stopCamera();
        // 可以得到摄像头的个数；此方法的返回值-1是Open方法的最大值；
        // Camera.getNumberOfCameras();
        // 不带参数 打开默认摄像头；如果带int参数表示打开指定的摄像头
        // 一般0表示的后置摄像头，1表示前置后置摄像头
        LogUtils.kLog().e("Camera.getNumberOfCameras:"+mCamera.getNumberOfCameras());
        try {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        }catch (Exception e){
            showDialogTimes++;
            if (!(showDialogTimes==1))
                showAlertDialog();
            else
                showDialogTimes=0;
        }



        if(mCamera!=null){
            mCamera.setDisplayOrientation(0);
            mParameters = mCamera.getParameters();
            //自动对焦
            mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            //获取支持的闪光灯模式
            mSupportFlash = mParameters.getSupportedFlashModes();
//adapteration
//        List<Camera.Size> supportedPreviewSizes = mParameters.getSupportedPreviewSizes();
//
//        Camera.Size previewSize = supportedPreviewSizes.get(getPictureSize(supportedPreviewSizes));
//                //findBestPreviewSize(mParameters);
//                //getOptimalPreviewSize(supportedPreviewSizes,width,height);
//        mParameters.setPreviewSize(previewSize.width, previewSize.height);
//        List<Camera.Size> supportedPictureSizes = mParameters.getSupportedPictureSizes();
//        Camera.Size pictureSize = supportedPictureSizes.get(getPictureSize(supportedPictureSizes));
//                //findBestPictureSize(mParameters);
//                //getOptimalPreviewSize(supportedPictureSizes,width,height);
//                mParameters.setPictureSize(pictureSize.width, pictureSize.height);
//        mCamera.setParameters(mParameters);
//
            //        =====================================
            List<Camera.Size> previewSizeList = mParameters
                    .getSupportedPreviewSizes();
            int previewWidth = 0;
            int previewHeight = 0;
            for (int i = 0; i < previewSizeList.size() - 1; i++) {
                previewWidth = previewSizeList.get(i).width;
                previewHeight = previewSizeList.get(i).height;
                int nextWidth = previewSizeList.get(i + 1).width;
                int nextHeight = previewSizeList.get(i + 1).height;
                if (previewWidth < nextWidth) {
                    previewWidth = nextWidth;
                }
                if (previewHeight < nextHeight) {
                    previewHeight = nextHeight;
                }
            }
            previewWidth = previewWidth > previewSizeList.get(0).width ? previewWidth
                    : previewSizeList.get(0).width;
            previewHeight = previewHeight > previewSizeList.get(0).height ? previewHeight
                    : previewSizeList.get(0).height;

            // debug
            /* WindowManager wm = getWindowManager();
            int screenHeight = wm.getDefaultDisplay().getHeight();
            int screenWidth = wm.getDefaultDisplay().getWidth();
            previewWidth = previewWidth > screenWidth ? screenWidth : previewWidth;
            previewHeight = previewHeight > screenHeight ? screenHeight : previewHeight; */
            // debug end
            mParameters.setPreviewSize(previewWidth, previewHeight);

            List<Camera.Size> supportedPictureSizesList = mParameters
                    .getSupportedPictureSizes();
            int supportedPictureWidth = 0;
            int supportedPictureHeight = 0;
            for (int i = 0; i < supportedPictureSizesList.size() - 1; i++) {
                supportedPictureWidth = supportedPictureSizesList.get(i).width;
                supportedPictureHeight = supportedPictureSizesList.get(i).height;
                int nextWidth = supportedPictureSizesList.get(i + 1).width;
                int nextHeight = supportedPictureSizesList.get(i + 1).height;
                if (supportedPictureWidth < nextWidth) {
                    supportedPictureWidth = nextWidth;
                }
                if (supportedPictureHeight < nextHeight) {
                    supportedPictureHeight = nextHeight;
                }
            }
            supportedPictureWidth = supportedPictureWidth > supportedPictureSizesList
                    .get(0).width ? supportedPictureWidth
                    : supportedPictureSizesList.get(0).width;
            supportedPictureHeight = supportedPictureHeight > supportedPictureSizesList
                    .get(0).height ? supportedPictureHeight
                    : supportedPictureSizesList.get(0).height;
            mParameters.setPictureSize(supportedPictureWidth,
                    supportedPictureHeight);

            //        =====================================
            mCamera.setParameters(mParameters);

            // 不需要闪光灯
            // refreshFlashMode();
            try {
                mCamera.setPreviewDisplay(mHolder);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            try {
                mCamera.startPreview();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void showAlertDialog() {
        new PromptDialog(this).setDialogType(PromptDialog.DIALOG_TYPE_WRONG)
                .setTitleText(getString(R.string.permission_decline)).setContentText(getString(R.string.camera_permission))
                .setPositiveListener(getString(R.string.i_know), new PromptDialog.OnPositiveListener() {
                    @Override
                    public void onClick(PromptDialog dialog) {
                        dialog.dismiss();
                        mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
                        NewCameraActivity.this.finish();
                    }
                }).show();

    }

    /** 刷新闪光灯按钮上的图片状态 */
    /*private void refreshFlashMode() {
        // 得到当前的闪光灯状态
        String mode = mParameters.getFlashMode();
        // 得到当前闪光灯模式在列表中的下标；

        if (mSupportFlash == null) {
            return;
        }
        mIndexFlash = mSupportFlash.indexOf(mode);
        if ("off".equals(mode)) {
            btnFlash.setText("off");
        } else if ("on".equals(mode)) {
            btnFlash.setText("on");
        } else if ("auto".equals(mode)) {
            btnFlash.setText("auto");
        } else if ("torch".equals(mode)){
            btnFlash.setText("torch");
        }
    }*/

    private void stopCamera() {

        if (mCamera != null) {
            // 停止预览
            mCamera.stopPreview();
            // 释放相机资源
            mCamera.release();
        }
        mCamera = null;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_ID_CAMERA_START: {
                    if (mIsActivityTeady && mIsSurfaceTeady) {
                        startCamera();

                    } else if (mIsActivityTeady || mIsSurfaceTeady) {
                        // 移除其他正在等待的消息，即同时只能有一个消息在等待；
                        removeMessages(MSG_ID_CAMERA_START);
                        sendEmptyMessageDelayed(MSG_ID_CAMERA_START, SLEEP_TIME);
                    }
                    break;
                }

                case MSG_ID_CAMERA_STOP: {
                    removeMessages(MSG_ID_CAMERA_START);
                    removeMessages(MSG_ID_CAMERA_STOP);
                    stopCamera();
                    break;
                }
                default:
                    break;
            }
        }

    };
//获取最佳尺寸方法一 [变形]
//    private int getPictureSize(List<Camera.Size> sizes) {
//        WindowManager wm = this.getWindowManager();
//        int screenWidth = wm.getDefaultDisplay().getWidth();
//// 屏幕的宽度
//        int index = -1;
//        for (int i = 0; i < sizes.size(); i++) {
//            if (Math.abs(screenWidth - sizes.get(i).width) == 0) {
//                index = i;
//                break;
//            }
//        }
//// 当未找到与手机分辨率相等的数值,取列表中间的分辨率
//        if (index == -1) {
//            index = sizes.size() / 2;
//        }
//        return index;
//    }
//获取最佳尺寸方法二[变形]
//    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int width, int height) {
//        final double ASPECT_TOLERANCE = 0.05;
//        double targetRatio = (double) width / height;
//        if (sizes == null)
//            return null;
//
//        Camera.Size optimalSize = null;
//        double minDiff = Double.MAX_VALUE;
//
//        int targetHeight = height;
//
//        // Try to find an size match aspect ratio and size
//        for (Camera.Size size : sizes) {
//            double r = size.width*1.0/size.height*1.0;
//            if(r!=4/3 || r!=3/4 || r!=16/9 || r!=9/16){
//                continue;
//            }
//
//            double ratio = (double) size.width / size.height;
//            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
//                continue;
//            if (Math.abs(size.height - targetHeight) < minDiff) {
//                optimalSize = size;
//                minDiff = Math.abs(size.height - targetHeight);
//            }
//        }
//
//        // Cannot find the one match the aspect ratio, ignore the requirement
//        if (optimalSize == null) {
//            minDiff = Double.MAX_VALUE;
//            for (Camera.Size size : sizes) {
//                if (Math.abs(size.height - targetHeight) < minDiff) {
//                    optimalSize = size;
//                    minDiff = Math.abs(size.height - targetHeight);
//                }
//            }
//        }
//        return optimalSize;
//    }
//方法三 空指针
//    private Camera.Size findBestPictureSize(Camera.Parameters parameters) {
//        int  diff = Integer.MIN_VALUE;
//        String pictureSizeValueString = parameters.get("picture-size-values");
//
//        // saw this on Xperia
//        if (pictureSizeValueString == null) {
//            pictureSizeValueString = parameters.get("picture-size-value");
//        }
//
//        if(pictureSizeValueString == null) {
//            return  mCamera.new Size(getScreenWH().widthPixels,getScreenWH().heightPixels);
//        }
//
//        LogUtils.kLog().e("tag", "pictureSizeValueString : " + pictureSizeValueString);
//        int bestX = 0;
//        int bestY = 0;
//
//
//        for(String pictureSizeString : ",".split(pictureSizeValueString))
//        {
//            pictureSizeString = pictureSizeString.trim();
//
//            int dimPosition = pictureSizeString.indexOf('x');
//            if(dimPosition == -1){
//                LogUtils.kLog().e("Bad pictureSizeString:" + pictureSizeString);
//                continue;
//            }
//
//            int newX = 0;
//            int newY = 0;
//
//            try{
//                newX = Integer.parseInt(pictureSizeString.substring(0, dimPosition));
//                newY = Integer.parseInt(pictureSizeString.substring(dimPosition+1));
//            }catch(NumberFormatException e){
//                LogUtils.kLog().e( "Bad pictureSizeString:" + pictureSizeString);
//                continue;
//            }
//
//            Point screenResolution = new Point (getScreenWH().widthPixels,getScreenWH().heightPixels);
//
//            int newDiff = Math.abs(newX - screenResolution.x)+Math.abs(newY- screenResolution.y);
//            if(newDiff == diff)
//            {
//                bestX = newX;
//                bestY = newY;
//                break;
//            } else if(newDiff > diff){
//                if((3 * newX) == (4 * newY)) {
//                    bestX = newX;
//                    bestY = newY;
//                    diff = newDiff;
//                }
//            }
//        }
//
//        if (bestX > 0 && bestY > 0) {
//            return mCamera.new Size(bestX, bestY);
//        }
//        return null;
//    }
//
//    private Camera.Size findBestPreviewSize(Camera.Parameters parameters) {
//
//        String previewSizeValueString = null;
//        int diff = Integer.MAX_VALUE;
//        previewSizeValueString = parameters.get("preview-size-values");
//
//        if (previewSizeValueString == null) {
//            previewSizeValueString = parameters.get("preview-size-value");
//        }
//
//        if(previewSizeValueString == null) {  // 有些手机例如m9获取不到支持的预览大小   就直接返回屏幕大小
//            return  mCamera.new Size(getScreenWH().widthPixels,getScreenWH().heightPixels);
//        }
//        LogUtils.kLog().d("tag", "previewSizeValueString : " + previewSizeValueString);
//        int bestX = 0;
//        int bestY = 0;
//
//        for(String prewsizeString : ",".split(previewSizeValueString))
//        {
//            prewsizeString = prewsizeString.trim();
//
//            int dimPosition = prewsizeString.indexOf('x');
//            if(dimPosition == -1){
//                LogUtils.kLog().e( "Bad prewsizeString:" + prewsizeString);
//                continue;
//            }
//
//            int newX = 0;
//            int newY = 0;
//
//            try{
//                newX = Integer.parseInt(prewsizeString.substring(0, dimPosition));
//                newY = Integer.parseInt(prewsizeString.substring(dimPosition+1));
//            }catch(NumberFormatException e){
//                LogUtils.kLog().e("Bad prewsizeString:" + prewsizeString);
//                continue;
//            }
//
//            Point screenResolution = new Point (getScreenWH().widthPixels,getScreenWH().heightPixels);
//
//            int newDiff = Math.abs(newX - screenResolution.x)+Math.abs(newY- screenResolution.y);
//
//            if(newDiff == diff)
//            {
//                bestX = newX;
//                bestY = newY;
//                break;
//            } else if(newDiff < diff){
//                if((3 * newX) == (4 * newY)) {
//                    bestX = newX;
//                    bestY = newY;
//                    diff = newDiff;
//                }
//            }
//        }
//        if (bestX > 0 && bestY > 0) {
//            return mCamera.new Size(bestX, bestY);
//        }
//        return null;
//    }
//
//    protected DisplayMetrics getScreenWH() {
//        DisplayMetrics dMetrics = new DisplayMetrics();
//        dMetrics = this.getResources().getDisplayMetrics();
//        return dMetrics;
//    }

//方法四 1+2001手机没问题 不变型了 质量损伤 操
//    private int getPictureSize(List<Camera.Size> sizes) {
//        WindowManager wm = this.getWindowManager();
//        int screenWidth = wm.getDefaultDisplay().getWidth();
//// 屏幕的宽度
//        int index = -1;
//        for (int i = 0; i < sizes.size(); i++) {
//            if (Math.abs(screenWidth - sizes.get(i).width) == 0) {
//                index = i;
//                break;
//            }
//        }
//// 当未找到与手机分辨率相等的数值,取列表中间的分辨率
//        if (index == -1) {
//            index = sizes.size() / 2;
//        }
//        return index;
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mHandler.sendEmptyMessage(MSG_ID_CAMERA_STOP);
            finish();
        }
        return false;
    }




}
